<template>
  <div class="common-layout">
    <el-container class="layout-container">
      <el-aside :width="isCollapse ? '64px' : '200px'" class="transition-width">
        <div class="logo-container">
          <img src="../assets/logo.png" alt="Logo" class="logo" v-if="!isCollapse">
          <el-icon class="collapse-btn" @click="toggleCollapse">
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
        </div>
        <el-menu :router="true" class="el-menu-vertical" background-color="#545c64" text-color="#fff"
          active-text-color="#ffd04b" :collapse="isCollapse" :default-active="route.path">
          <!-- 数据看板 - 所有人可见 -->
          <el-menu-item index="/home/dashboard">
            <el-icon>
              <DataLine />
            </el-icon>
            <template #title>数据看板</template>
          </el-menu-item>
          
          <!-- 公司相关菜单 - 除了老师都可见 -->
          <el-sub-menu index="/home/company" v-if="!hasRole(4)">
            <template #title>
              <el-icon>
                <OfficeBuilding />
              </el-icon>
              <span>公司相关</span>
            </template>
            
            <!-- 广告管理子菜单 -->
            <el-sub-menu index="/home/company/ad">
              <template #title>
                <el-icon>
                  <Picture />
                </el-icon>
                <span>广告管理</span>
              </template>
              <el-menu-item index="/home/company/ad/list">广告列表</el-menu-item>
              <el-menu-item index="/home/company/ad/upload">广告上传</el-menu-item>
            </el-sub-menu>
            
            <!-- 库存管理子菜单 -->
            <el-sub-menu index="/home/company/inventory" v-if="hasPermission('product:all') || hasPermission('product:edit') || hasPermission('admin:all')">
              <template #title>
                <el-icon>
                  <Box />
                </el-icon>
                <span>库存管理</span>
              </template>
              <el-menu-item index="/home/company/inventory/list">库存列表</el-menu-item>
              <el-menu-item index="/home/company/inventory/publish">发布库存</el-menu-item>
            </el-sub-menu>
            
            <!-- 员工管理 - 只有超管、管理员、主管可见 -->
            <el-menu-item index="/home/company/employees" v-if="hasPermission('employee:manage') || hasPermission('admin:manage') || hasPermission('admin:all')">
              <el-icon><UserFilled /></el-icon>
              <span>员工管理</span>
            </el-menu-item>
          </el-sub-menu>
          
          <!-- 用户管理菜单 - 有用户查看权限的可见 -->
          <el-sub-menu index="/home/users" v-if="hasPermission('user:view') || hasPermission('admin:all')">
            <template #title>
              <el-icon>
                <User />
              </el-icon>
              <span>用户管理</span>
            </template>
            <!-- 小程序用户管理 -->
            <el-menu-item index="/home/users/app-list">小程序用户列表</el-menu-item>
            <!-- 后台用户管理 -->
            <el-menu-item index="/home/users/admin-list">后台用户列表</el-menu-item>
          </el-sub-menu>
          
          <!-- 小程序管理菜单，仅超级管理员可见 -->
          <el-sub-menu index="/home/miniapp" v-if="hasPermission('admin:all') || hasPermission('admin:manage')">
            <template #title>
              <el-icon>
                <Cellphone />
              </el-icon>
              <span>小程序管理</span>
            </template>
            <el-menu-item index="/home/miniapp/banners">轮播图管理</el-menu-item>
            <el-menu-item index="/home/miniapp/data-upload">数据上传</el-menu-item>
            <el-menu-item index="/home/miniapp/file-upload">文件上传</el-menu-item>
          </el-sub-menu>
          
          <!-- 社区管理菜单 -->
          <el-sub-menu index="/home/community" v-if="hasPermission('community:manage') || hasPermission('admin:all')">
            <template #title>
              <el-icon>
                <ChatDotRound />
              </el-icon>
              <span>社区管理</span>
            </template>
            <el-menu-item index="/home/community/posts">帖子管理</el-menu-item>
            <el-menu-item index="/home/community/comments">评论管理</el-menu-item>
          </el-sub-menu>
          
          <!-- 教学管理菜单，仅老师和超级管理员可见 -->
          <el-sub-menu index="/home/teaching" v-if="hasPermission('course:manage') || hasPermission('admin:all')">
            <template #title>
              <el-icon>
                <Reading />
              </el-icon>
              <span>教学管理</span>
            </template>
            <el-menu-item index="/home/teaching/school">学校信息</el-menu-item>
            <el-menu-item index="/home/teaching/students">学生信息</el-menu-item>
          </el-sub-menu>
          
          <!-- 审核管理菜单 - 有管理权限的可见 -->
          <el-sub-menu index="/home/audit" v-if="hasPermission('admin:all') || hasPermission('admin:manage') || hasPermission('employee:manage')">
            <template #title>
              <el-icon>
                <Check />
              </el-icon>
              <span>审核管理</span>
            </template>
            <el-menu-item index="/home/audit/inventory" v-if="hasPermission('product:all') || hasPermission('admin:all')">库存审核</el-menu-item>
            <el-menu-item index="/home/audit/students" v-if="hasPermission('course:manage') || hasPermission('admin:all')">学生审核</el-menu-item>
            <el-menu-item index="/home/audit/users" v-if="hasPermission('user:edit') || hasPermission('admin:all')">后台用户审核</el-menu-item>
            <el-menu-item index="/home/audit/posts" v-if="hasPermission('community:manage') || hasPermission('admin:all')">帖子审核</el-menu-item>
            <el-menu-item index="/home/audit/comments" v-if="hasPermission('community:manage') || hasPermission('admin:all')">评论审核</el-menu-item>
          </el-sub-menu>
          
          <!-- 系统设置 - 所有人可见 -->
          <el-menu-item index="/home/settings">
            <el-icon>
              <Setting />
            </el-icon>
            <template #title>系统设置</template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header>
          <div class="header-container">
            <div class="breadcrumb">
              <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home/dashboard' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>{{ currentRoute }}</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div class="user-info">
              <el-dropdown trigger="click">
                <span class="user-dropdown">
                  <el-avatar :size="32" :src="userAvatar" @error="handleAvatarError">
                    {{ userInfo?.username?.charAt(0)?.toUpperCase() }}
                  </el-avatar>
                  <span class="username">{{ userInfo?.username || '管理员' }}</span>
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleProfile">
                      <el-icon><UserFilled /></el-icon>
                      个人信息
                    </el-dropdown-item>
                    <el-dropdown-item divided @click="handleLogout">
                      <el-icon><SwitchButton /></el-icon>
                      退出登录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-header>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  DataLine, Box, Document, User, Fold, Expand, 
  Setting, ArrowDown, UserFilled, SwitchButton,
  Cellphone, OfficeBuilding, PieChart, Reading,
  Check, Picture, ChatDotRound
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../store/user'

const isCollapse = ref(false)
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 获取用户信息
const userInfo = computed(() => userStore.userInfo)
const hasPermission = userStore.hasPermission

// 检查用户角色
const hasRole = (roleId) => {
  return userInfo.value?.role === roleId
}

// 用户头像
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
const userAvatar = computed(() => userInfo.value?.avatar || defaultAvatar)

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const currentRoute = computed(() => {
  const routeMap = {
    '/home/dashboard': '数据看板',
    // 公司相关
    '/home/company/ad/list': '广告列表',
    '/home/company/ad/upload': '广告上传',
    '/home/company/inventory/list': '库存列表',
    '/home/company/inventory/publish': '发布库存',
    '/home/company/employees': '员工管理',
    // 用户管理
    '/home/users/app-list': '小程序用户列表',
    '/home/users/admin-list': '后台用户列表',
    '/home/users/profile': '个人信息',
    // 小程序管理
    '/home/miniapp/banners': '轮播图管理',
    '/home/miniapp/data-upload': '数据上传',
    '/home/miniapp/file-upload': '文件上传',
    // 社区管理
    '/home/community/posts': '帖子管理',
    '/home/community/comments': '评论管理',
    // 教学管理
    '/home/teaching/school': '学校信息',
    '/home/teaching/students': '学生信息',
    // 审核管理
    '/home/audit/inventory': '库存审核',
    '/home/audit/students': '学生审核',
    '/home/audit/users': '后台用户审核',
    '/home/audit/posts': '帖子审核',
    '/home/audit/comments': '评论审核',
    // 系统设置
    '/home/settings': '系统设置'
  }

  // 自动解析多级路由（示例：/home/users/list/edit -> 用户列表/编辑）
  const paths = route.path.split('/').filter(p => p)
  if (paths.length > 3) {
    const basePath = `/${paths.slice(0,3).join('/')}`
    return `${routeMap[basePath] || paths[2]} / ${paths[3]}`
  }

  return routeMap[route.path] || '首页'
})

// 处理头像加载错误
const handleAvatarError = () => {
  console.warn('头像加载失败，使用默认头像')
}

// 个人信息页面
const handleProfile = () => {
  router.push('/home/users/profile')
}

// 完善退出登录处理函数
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用store中的logout方法
    userStore.logout()
  }).catch(() => {
    // 取消退出
  })
}
</script>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;
}

.transition-width {
  transition: width 0.3s;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background-color: #4a5259;

  .logo {
    height: 40px;
    object-fit: contain;
  }

  .collapse-btn {
    color: #fff;
    cursor: pointer;
    font-size: 20px;

    &:hover {
      color: #ffd04b;
    }
  }
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
  padding: 0 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.user-info {
  .user-dropdown {
    display: flex;
    align-items: center;
    cursor: pointer;

    .username {
      margin-left: 8px;
      margin-right: 4px;
      color: #606266;
    }
    
    .el-icon--right {
      font-size: 12px;
      margin-top: 2px;
    }
  }
}

.el-aside {
  background-color: #545c64;
}

.el-menu-vertical {
  border-right: none;
}

.el-main {
  background-color: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
}

.breadcrumb {
  line-height: 60px;
}

// 增加菜单过渡效果
.el-menu-vertical {
  transition: all 0.3s;
  
  .el-submenu__title:hover {
    background-color: rgba(255, 255, 255, 0.1) !important;
  }
  
  .el-menu-item:hover {
    background-color: rgba(255, 255, 255, 0.1) !important;
  }
  
  .el-menu-item.is-active {
    background-color: #409EFF !important;
  }
}

// 下拉菜单样式优化
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  
  .el-icon {
    margin-right: 8px;
    font-size: 16px;
  }
}

// 多级菜单样式优化
:deep(.el-menu--inline) {
  .el-menu-item {
    padding-left: 50px !important;
  }
}

// 响应式处理
@media (max-width: 768px) {
  .layout-container {
    .el-aside {
      width: 64px !important;
      
      .logo {
        display: none;
      }
    }
    
    .el-menu--collapse {
      .el-submenu > .el-submenu__title span {
        display: none;
      }
    }
    
    .username {
      display: none;
    }
  }
}
</style>